package com.coffee.websocket.metadata;

import lombok.*;

import java.nio.ByteBuffer;

/**
 * 二进制 消息 格式
 * 前端必须遵从 该规则
 *
 * @author: songkui
 * @since: 2023/2/21 18:05
 */
@Setter
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MochaBinaryProtocol<T extends MochaBasicBinaryMessage> {
    private byte type;  //消息类型  1, chat  2, Binary
    private int cmd;
    private int state = 200;  // state 状态； [前端请求消息： 传0占位即可； response 则需要赋值]
    private T data;

    public MochaBinaryProtocol(byte type, int cmd, int state){
        this.type = type;
        this.cmd = cmd;
        this.state = state;
    }

    public ByteBuffer encode(){
        ByteBuffer byteBuffer = ByteBuffer.allocate(9 + data.length());
        byteBuffer.put(this.getType());
        byteBuffer.putInt(this.getCmd());
        byteBuffer.putInt(this.getState());
        data.encode(byteBuffer);

        byteBuffer.flip();
        return byteBuffer;
    }


}
